/**
 * 交错动画列表组件
 * 子元素按顺序依次出现，创造流畅的视觉效果
 */

"use client"

import { ReactNode, Children, cloneElement, isValidElement } from "react"
import { cn } from "@/lib/utils"

interface StaggerListProps {
  children: ReactNode
  staggerDelay?: number
  baseDelay?: number
  className?: string
  animation?: 'fade' | 'slide-up' | 'slide-down' | 'slide-left' | 'slide-right' | 'scale'
}

export function StaggerList({
  children,
  staggerDelay = 50,
  baseDelay = 0,
  className = '',
  animation = 'slide-up',
}: StaggerListProps) {
  const animationClasses = {
    'fade': 'animate-in fade-in',
    'slide-up': 'animate-in fade-in slide-in-from-bottom-3',
    'slide-down': 'animate-in fade-in slide-in-from-top-3',
    'slide-left': 'animate-in fade-in slide-in-from-right-3',
    'slide-right': 'animate-in fade-in slide-in-from-left-3',
    'scale': 'animate-in fade-in zoom-in-95',
  }

  const childrenArray = Children.toArray(children)

  return (
    <div className={className}>
      {childrenArray.map((child, index) => {
        if (!isValidElement(child)) return child

        const delay = baseDelay + index * staggerDelay

        return cloneElement(child, {
          ...child.props,
          className: cn(
            child.props.className,
            animationClasses[animation]
          ),
          style: {
            ...child.props.style,
            animationDelay: `${delay}ms`,
            animationDuration: '400ms',
            animationFillMode: 'both',
          },
          key: child.key || index,
        } as any)
      })}
    </div>
  )
}

/**
 * 网格交错动画组件
 * 适用于卡片网格布局
 */
interface StaggerGridProps {
  children: ReactNode
  cols?: number
  staggerDelay?: number
  className?: string
}

export function StaggerGrid({
  children,
  cols = 3,
  staggerDelay = 30,
  className = '',
}: StaggerGridProps) {
  const childrenArray = Children.toArray(children)

  return (
    <div className={cn('grid gap-4', className)}>
      {childrenArray.map((child, index) => {
        if (!isValidElement(child)) return child

        // 计算交错延迟（按行列顺序）
        const row = Math.floor(index / cols)
        const col = index % cols
        const delay = (row + col) * staggerDelay

        return cloneElement(child, {
          ...child.props,
          className: cn(
            child.props.className,
            'animate-in fade-in slide-in-from-bottom-2'
          ),
          style: {
            ...child.props.style,
            animationDelay: `${delay}ms`,
            animationDuration: '500ms',
            animationFillMode: 'both',
          },
          key: child.key || index,
        } as any)
      })}
    </div>
  )
}


